package com.my.transaction.service.impl;

import com.my.transaction.entity.Account;
import com.my.transaction.JDBCUtil;
import com.my.transaction.dao.impl.AccountDaoImpl;
import com.my.transaction.service.AccountService;

import java.sql.SQLException;

public class AccountServiceImpl implements AccountService {

    @Override
    public void transfer(int fromcardId, int tocardId, int money) {
        AccountDaoImpl accountDao = new AccountDaoImpl();

        //开启事务
        try{
            JDBCUtil.beginTransaction();
            Account fromAccount = accountDao.queryAccountByCard(fromcardId);//付款方
            Account toAccount = accountDao.queryAccountByCard(tocardId);//收款方
            //转账
            if(fromAccount.getBalance() > money){
                int fromBalance = fromAccount.getBalance() - money;
                fromAccount.setBalance(fromBalance);
                int toBalance = toAccount.getBalance() + money;
                toAccount.setBalance(toBalance);
                accountDao.updateAccount(fromAccount);
                accountDao.updateAccount(toAccount);
                System.out.println("转账成功！");
                JDBCUtil.commitTransaction();
            }else{
                System.out.println("账户余额不足！");
            }
        }catch (Exception e){
            try{
                JDBCUtil.rollbackTransaction();
                System.out.println("转账失败，回滚！");
            }catch (SQLException f){
                f.printStackTrace();
            }
            e.printStackTrace();
        }finally {
            try {
                JDBCUtil.close();
            }catch (SQLException e){
                e.printStackTrace();
            }
        }
    }
}
